//
//  WDCustomViewController.m
//  WDPolymerizeSDK
//
//  Created by little People on 2023/6/8.
//

#import "WDCustomViewController.h"
#import "WDNSLog.h"
#import "WDCardZDYManager.h"
#import "WDSourceManager.h"
#import "WDCustomManager.h"
#import "WDCallBackManager.h"
#import "WDAdStatusManager.h"
#import  <AVFoundation/AVFoundation.h>
@interface WDCustomViewController ()
@property (nonatomic ,strong) AVPlayer * avplayer;

@property (nonatomic ,strong) AVPlayerItem * avplayerItem;

@property (nonatomic ,strong) AVPlayerLayer * playLayer;

@property (nonatomic, strong) WDCustomCardModel *model;

@property (nonatomic, strong)UIButton *closeVideoButton;

@property (nonatomic, strong)NSTimer *countdownTimer;

//原生展示激励15s
//原生展示插屏5s
@property (nonatomic, assign)NSInteger count;

@property (nonatomic, assign)CMTime time;

@property (nonatomic, assign)CGFloat safeAreaTop;

@property (nonatomic, assign)CGFloat safeAreaBottom;
@end

@implementation WDCustomViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.safeAreaTop = 0.0;
    self.safeAreaBottom = 0.0;
    if (@available(iOS 11.0, *)) {
        UIViewController *rootViewController = [[[UIApplication sharedApplication].windows objectAtIndex:0] rootViewController];
        self.safeAreaTop = rootViewController.view.safeAreaInsets.top;
        self.safeAreaBottom = rootViewController.view.safeAreaInsets.bottom;
    }
    
    self.count = [WDCustomManager shareCustomManager].customCout;
    self.model = [[WDCardZDYManager shareCardZDYManager] getCustomCardModel];
    self.view.backgroundColor = [UIColor blackColor];
//    [self adad];
    
    [self playVideo];
    [self topUI];
    [self bottomView];
    if (self.model) {
        [[WDAdStatusManager shareStatusManager] customAdShowWithEventName:SELF_EVENT_NAME package:self.model.packName creative:self.model.adTitle];
        [[WDCallBackManager shareCallBackManager] adCallBackWithType:Show adSpace:[WDCallBackModel shareCallBackModel].adSpace message:@""];
    }else{
        [[WDCallBackManager shareCallBackManager] adCallBackWithType:ShowFail adSpace:[WDCallBackModel shareCallBackModel].adSpace message:@"no data"];
    }
    
    // Do any additional setup after loading the view.
}

- (void)topUI
{
    UIButton *attentionButton = [[UIButton alloc] initWithFrame:CGRectMake(20, self.safeAreaTop+40, 20, 20)];
    [attentionButton setBackgroundImage:[WDSourceManager WDImageWithName:@"attention"] forState:UIControlStateNormal];
    [self.view addSubview:attentionButton];
    
    UIButton *soundButton = [[UIButton alloc] initWithFrame:CGRectMake(attentionButton.frame.origin.x+attentionButton.frame.size.width+10, attentionButton.frame.origin.y-2.5, attentionButton.frame.size.width+5, attentionButton.frame.size.height+5)];
    [soundButton setBackgroundImage:[WDSourceManager WDImageWithName:@"sound"] forState:UIControlStateNormal];
    [soundButton setBackgroundImage:[WDSourceManager WDImageWithName:@"mute"] forState:UIControlStateSelected];
    [soundButton addTarget:self action:@selector(clickSoundButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:soundButton];
    
    self.closeVideoButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-20-30, attentionButton.frame.origin.y, 30, 30)];
//    self.closeVideoButton.hidden = YES;
//    [self.closeVideoButton setBackgroundImage:[WDSourceManager WDImageWithName:@"close"] forState:UIControlStateNormal];
    
    [self.closeVideoButton addTarget:self action:@selector(clickCloseVideoButton:) forControlEvents:UIControlEventTouchUpInside];
    self.closeVideoButton.userInteractionEnabled = NO;
    self.closeVideoButton.center = CGPointMake(self.closeVideoButton.center.x, soundButton.center.y);
    [self.view addSubview:self.closeVideoButton];
    
    
}

- (void)countdown:(NSTimer *)timer
{
    self.count--;
    if (self.count < 0)
    {
        [self.countdownTimer invalidate];
        self.countdownTimer = nil;
        [self.closeVideoButton setTitle:@"" forState:UIControlStateNormal];
        [self.closeVideoButton setBackgroundImage:[WDSourceManager WDImageWithName:@"close1"] forState:UIControlStateNormal];
        self.closeVideoButton.userInteractionEnabled = YES;
    }else{
        [self.closeVideoButton setTitle:[NSString stringWithFormat:@"%lds",self.count] forState:UIControlStateNormal];
    }
    
}

- (void)clickCloseVideoButton:(UIButton *)sender
{
    WDLog(@"clickCloseVideoButton");
    [self showAdDetails];
}

- (void)clickSoundButton:(UIButton *)sender
{
    sender.selected = !sender.selected;
    self.avplayer.muted = sender.selected;
}

- (void)bottomView
{
    UIView *bottomV = [[UIView alloc] initWithFrame:CGRectMake(15, self.view.frame.size.height-10-60-self.safeAreaBottom, self.view.frame.size.width-30, 60)];
    bottomV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomV];
    
    UIImageView *iconIV = [[UIImageView alloc] initWithFrame:CGRectMake(15, 5, 50, 50)];
    iconIV.image = self.model.appIcon;
    iconIV.contentMode = UIViewContentModeScaleAspectFill;
    [bottomV addSubview:iconIV];
    
    UILabel *appNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(iconIV.frame.origin.x+iconIV.frame.size.width+10, iconIV.frame.origin.y, bottomV.frame.size.width/2, iconIV.frame.size.height/2)];
    appNameLabel.text = self.model.appName;
    [appNameLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:15]];
    appNameLabel.textColor = [UIColor blackColor];
    [bottomV addSubview:appNameLabel];
    
    UILabel *descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(appNameLabel.frame.origin.x, appNameLabel.frame.origin.y+appNameLabel.frame.size.height, appNameLabel.frame.size.width, appNameLabel.frame.size.height)];
    descriptionLabel.text = self.model.adDescription;
    descriptionLabel.font = [UIFont systemFontOfSize:13];
    descriptionLabel.textColor = [UIColor lightGrayColor];
    [bottomV addSubview:descriptionLabel];
    
    UIButton *installButton = [[UIButton alloc] initWithFrame:CGRectMake(bottomV.frame.size.width-10-80, iconIV.frame.origin.y, 80, iconIV.frame.size.height)];
    [installButton setTitle:@"Install" forState:UIControlStateNormal];
    [installButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [installButton setBackgroundColor:[UIColor redColor]];
    [installButton addTarget:self action:@selector(clickInstallButton:) forControlEvents:UIControlEventTouchUpInside];
    [bottomV addSubview:installButton];
}

- (void)clickInstallButton:(UIButton *)sender
{
    if (self.model.deepLink.length > 0)
    {
        [[WDAdStatusManager shareStatusManager] customAdClickWithEventName:SELF_EVENT_NAME package:self.model.packName creative:self.model.adTitle];
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.model.deepLink] options:@{} completionHandler:nil];
        }else{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.model.deepLink]];
        }
    }
}

- (void)playVideo{
    NSError *error = nil;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&error];

    //切回来前台继续播放的话，我们需要监听两个通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];


    
    NSString * webPath = self.model.videoUrl;
    NSURL* webUrl = [NSURL URLWithString:webPath];
    //初始化播放器
    self.avplayerItem = [[AVPlayerItem alloc] initWithURL:webUrl];
    self.avplayer = [[AVPlayer alloc] initWithPlayerItem:self.avplayerItem];
    self.avplayer.muted = NO;
    _playLayer = [AVPlayerLayer playerLayerWithPlayer:self.avplayer];
    _playLayer.videoGravity = AVLayerVideoGravityResize;
    _playLayer.frame = CGRectMake(0, 80, self.view.frame.size.width, self.view.frame.size.height-80-60);
    [self.view.layer addSublayer:_playLayer];
    //开始播放
    [self.avplayer play];
   
    //此通知是监听视频播放完成
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished) name:AVPlayerItemDidPlayToEndTimeNotification object:self.avplayer.currentItem];
    
    //kvo监听视频状态
    [self.avplayer.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
}

//等到切回前台的时候再继续播放
-(void)appBecomeActive:(NSNotification*)notification
{
    @try{[self.avplayer seekToTime:self.time toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:^(BOOL finished){
        if(finished)
        {
            [self.avplayer play];
        }
    }
    ];
        
    }
    @catch(NSException*exception){
        [self.avplayer play];
    }
}

//先在appWillResignActive:方法中记录当前播放的时间CMTime
-(void)appWillResignActive:(NSNotification*)notification
{
    if(self.avplayer)
    {
        [self.avplayer pause];
        self.time=self.avplayer.currentTime;
    }
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath

                      ofObject:(id)object

                        change:(NSDictionary *)change

                       context:(void*)context

{
    
    AVPlayerItem* playitem = (AVPlayerItem*)object;
    
    if([keyPath isEqualToString:@"status"]) {
        
        AVPlayerStatus status = [[change objectForKey:@"new"] intValue];
        
        switch(status) {
                
            case AVPlayerStatusReadyToPlay:{ //准备就绪
                
                //获取视频时间
                [self.closeVideoButton setTitle:[NSString stringWithFormat:@"%lds",self.count] forState:UIControlStateNormal];
                self.countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countdown:) userInfo:nil repeats:YES];
                WDLog(@"AVPlayerStatusReadyToPlay");
                
                break;
                
            }
                
            case AVPlayerStatusFailed:{ //失败、可以尝试重试
                [self.countdownTimer invalidate];
                self.countdownTimer = nil;
                [self.closeVideoButton setTitle:@"" forState:UIControlStateNormal];
                [self.closeVideoButton setBackgroundImage:[WDSourceManager WDImageWithName:@"close1"] forState:UIControlStateNormal];
                self.closeVideoButton.userInteractionEnabled = YES;
                break;
                
            }
                
            case AVPlayerStatusUnknown:{ //异常
                [self.countdownTimer invalidate];
                self.countdownTimer = nil;
                [self.closeVideoButton setTitle:@"" forState:UIControlStateNormal];
                [self.closeVideoButton setBackgroundImage:[WDSourceManager WDImageWithName:@"close1"] forState:UIControlStateNormal];
                self.closeVideoButton.userInteractionEnabled = YES;
                break;
                
            }
                
            default:
                
                break;
                
        }
        
    }
    
}

- (void)playbackFinished
{
    WDLog(@"playbackFinished");
    [self.countdownTimer invalidate];
    self.countdownTimer = nil;
    [self showAdDetails];
}

- (void)showAdDetails
{
    [self.avplayer pause];
    
    UIView *detailsV = [[UIView alloc] initWithFrame:self.view.bounds];
    detailsV.backgroundColor = [UIColor blackColor];
    [self.view addSubview:detailsV];
    
    UIImageView *bannerIV = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.safeAreaTop+20, detailsV.frame.size.width, 200)];
    bannerIV.image = self.model.bannerImage;
    bannerIV.contentMode = UIViewContentModeScaleAspectFill;
    [detailsV addSubview:bannerIV];
    
    UIButton *dismissButton = [[UIButton alloc] initWithFrame:CGRectMake(detailsV.frame.size.width-10-30, bannerIV.frame.origin.y+10, 30, 30)];
    [dismissButton setImage:[WDSourceManager WDImageWithName:@"close"] forState:UIControlStateNormal];
    [dismissButton addTarget:self action:@selector(clickDismissButton:) forControlEvents:UIControlEventTouchUpInside];
    [detailsV addSubview:dismissButton];
    
    UIButton *installButton = [[UIButton alloc] initWithFrame:CGRectMake(15, detailsV.frame.size.height-40-self.safeAreaBottom, detailsV.frame.size.width-30, 40)];
    [installButton setBackgroundColor:[UIColor redColor]];
    [installButton setTitle:@"INSTALL" forState:UIControlStateNormal];
    [installButton addTarget:self action:@selector(clickInstallButton:) forControlEvents:UIControlEventTouchUpInside];
    [detailsV addSubview:installButton];
    
    UILabel *descrLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, installButton.frame.origin.y-60-30, detailsV.frame.size.width, 30)];
    descrLabel.text = self.model.adDescription;
    descrLabel.textAlignment = NSTextAlignmentCenter;
    descrLabel.textColor = [UIColor whiteColor];
    descrLabel.font = [UIFont systemFontOfSize:15];
    [detailsV addSubview:descrLabel];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, descrLabel.frame.origin.y-5-30, detailsV.frame.size.width, 30)];
    titleLabel.text = self.model.adTitle;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    [titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:18]];
    [detailsV addSubview:titleLabel];
    
    UILabel *priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, titleLabel.frame.origin.y-50-20, detailsV.frame.size.width, 20)];
    priceLabel.text = @"Free  App Store";
    priceLabel.textColor = [UIColor whiteColor];
    priceLabel.font = [UIFont systemFontOfSize:13];
    priceLabel.textAlignment = NSTextAlignmentCenter;
    [detailsV addSubview:priceLabel];
    
    UIImageView *starImageView = [[UIImageView alloc] initWithFrame:CGRectMake(detailsV.center.x-50, priceLabel.frame.origin.y-10-20, 100, 20)];
    starImageView.image = [WDSourceManager WDImageWithName:self.model.rating];
    [detailsV addSubview:starImageView];
    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, starImageView.frame.origin.y-15-30, detailsV.frame.size.width, 30)];
    nameLabel.text = self.model.appName;
    nameLabel.textColor = [UIColor whiteColor];
    nameLabel.font = [UIFont systemFontOfSize:20];
    nameLabel.textAlignment = NSTextAlignmentCenter;
    [detailsV addSubview:nameLabel];
    
    UIImageView *iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(detailsV.center.x-30, nameLabel.frame.origin.y-10-60, 60, 60)];
//    iconImageView.center = self.adContentView.center;
    iconImageView.image = self.model.appIcon;
    iconImageView.layer.cornerRadius = 8.0;
    iconImageView.clipsToBounds = YES;
    [detailsV addSubview:iconImageView];
}

- (void)clickDismissButton:(UIButton *)sender
{
    [[WDCallBackManager shareCallBackManager] adCallBackWithType:Finish adSpace:[WDCallBackModel shareCallBackModel].adSpace message:@""];
    dispatch_async(dispatch_get_main_queue(), ^{
        [[self navigationController] dismissViewControllerAnimated:NO completion:^{
        }];
    });
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
